package com.amin.concurrent;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

import sun.net.www.content.audio.aiff;

/**
 * 测试原子性 原子型类型底层的实现原理是用锁来实现的
 */
public class AtomicDemo {
	//public static int num = 0;
	public static AtomicInteger ai = new AtomicInteger(0);

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch cdl = new CountDownLatch(2);
		new Thread(new AddRunner1(cdl)).start();
		new Thread(new AddRunner2(cdl)).start();
		cdl.await();
		//System.out.println(num);
		System.out.println(ai.get());
	}
}

class AddRunner1 implements Runnable {
	private CountDownLatch cdl;

	public AddRunner1(CountDownLatch cdl) {
		this.cdl = cdl;
	}

	public void run() {
		for (int i = 0; i < 100000000; i++) {
			AtomicDemo.ai.addAndGet(1);
//			synchronized(AtomicDemo.class){
//				AtomicDemo.num++;
//			} 
		}
		cdl.countDown();
	}
}

class AddRunner2 implements Runnable {
	private CountDownLatch cdl;

	public AddRunner2(CountDownLatch cdl) {
		this.cdl = cdl;
	}

	public void run() {
		for (int i = 0; i < 100000000; i++) {
			AtomicDemo.ai.addAndGet(1);
			/*synchronized(AtomicDemo.class){
				AtomicDemo.num++;
			}*/ 
		}
		cdl.countDown();
	}
}
